import { DeviceStorage } from "./DeviceStorage";
import { API } from "../api";

// 根据code登录
export async function login(code) {
    // 请求jwt
    const jwtRes = await API.getJwt(code)
    // {status: 200, code: 10000, msg: "登录成功", data: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJjZ…VyIn0.hm98O-cn4eFYaQSx08txgeGdB84aaAwmAp8i8m7yNko"}
    // code: 10000
    // data: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJjZjYwNzdiMzAwYmY4OGIzNDM4N2IxY2YxMjdlNzZlNCIsImV4cCI6MTU0OTA0OTc3MCwiaXNzIjoiZmNjIiwibmJmIjoxNTQ1NDQ5NzcwLCJzdWIiOiJ1c2VyIn0.hm98O-cn4eFYaQSx08txgeGdB84aaAwmAp8i8m7yNko"
    // msg: "登录成功"
    // status: 200}
    if (jwtRes.code === 10000) {
        const jwt = jwtRes.data
        await DeviceStorage.set('jwt', jwt)
        // 获取用户信息
        const userRes = await API.getUserInfo()
        if (userRes.code === 10000) {
            if (userRes.data instanceof Array) {
                await DeviceStorage.set('user_info', JSON.stringify(userRes.data[0]))
            } else {
                await DeviceStorage.set('user_info', JSON.stringify(userRes.data))
            }
        } else {
            console.log('get user info fail!');
        }
        return jwtRes
    } else {
        console.log('get jwt fail!');
        return false
    }
}


// 获取线上用户信息，存storage
export const getUserInfo = async () => {
    const jwt = await DeviceStorage.get('jwt')
    console.log('jwt', jwt);
    if (jwt) {
        const res = await API.getUserInfo()
        if (res && res.code && res.code === 10000) {
            await DeviceStorage.set('user_info', JSON.stringify(res.data))
        }
    } else {
        console.log('error: can not get jwt from storage.')
    }
}

// 从storage读取用户信息
export async function getUserInfoStorage() {
    const userInfoStr = await DeviceStorage.get('user_info')
    return JSON.parse(userInfoStr)
}

// user info
// AdUsername: "username"
// BankNumber: "6228481178256941173"
// BuyToken: "hkd"
// Freeze: 400
// Id: 1
// Max: 1000
// Min: 10
// SellToken: "fcc"
// TxFail: 0
// TxSuc: 5
// Type: 2
// Uid: 11
// Unit: 2
